package com.cxs.security;
import com.cxs.common.exception.CaptchaException;
import com.cxs.common.exception.MyLoginException;
import com.cxs.common.result.ResultVO;

import cn.hutool.json.JSONUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败的处理，实现AuthenticationFailureHandler
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
            throws IOException, ServletException, CaptchaException {
        // 设置响应类型为 JSON 格式的字符串，如果不加这句话，那么浏览器显示的将是乱码
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ServletOutputStream outputStream = response.getOutputStream();
        // 默认是用户登录异常
        ResultVO resultVO = null;
        if (exception.getCause() instanceof MyLoginException) {
            resultVO = new ResultVO(((MyLoginException) exception.getCause()).getCode());
        } else if (exception instanceof CaptchaException) {
            resultVO = new ResultVO("A0201");
        } else {
            resultVO = new ResultVO("A0200");
        }
        // 向客户端浏览器输出数据
        outputStream.write(JSONUtil.toJsonStr(resultVO).getBytes("UTF-8"));
        outputStream.flush();
        outputStream.close();
    }
}